<template>
  <div class="outbound-records">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>出库记录</h1>
      <div class="breadcrumb">仓库管理 > 出库记录</div>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <div class="search-form">
        <div class="form-item">
          <label>出库单号</label>
          <input v-model="searchForm.deliveryCode" type="text" placeholder="请输入出库单号" />
        </div>
        <div class="form-item">
          <label>商品名称</label>
          <input v-model="searchForm.productName" type="text" placeholder="请输入商品名称" />
        </div>
        <div class="form-item">
          <label>仓库</label>
          <select v-model="searchForm.warehouseId">
            <option value="">全部</option>
            <option v-for="item in warehouses" :key="item.id" :value="item.id">{{ item.whName }}</option>
          </select>
        </div>
        <div class="form-item">
          <label>开始日期</label>
          <input v-model="searchForm.startDate" type="date" />
        </div>
        <div class="form-item">
          <label>结束日期</label>
          <input v-model="searchForm.endDate" type="date" />
        </div>
        <div class="form-buttons">
          <button class="btn btn-primary" @click="fetchRecords">查询</button>
          <button class="btn btn-secondary" @click="resetSearch">重置</button>
          <button class="btn btn-success" @click="exportRecords">导出</button>
        </div>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="stats-section">
      <div class="stats-grid">
        <div class="stat-card">
          <div class="stat-icon">
            <i class="icon-box"></i>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ totalRecords }}</div>
            <div class="stat-label">总出库记录</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">
            <i class="icon-package"></i>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ totalQuantity }}</div>
            <div class="stat-label">总出库数量</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">
            <i class="icon-warehouse"></i>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ uniqueWarehouses }}</div>
            <div class="stat-label">涉及仓库</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">
            <i class="icon-product"></i>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ uniqueProducts }}</div>
            <div class="stat-label">涉及商品</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 出库记录列表 -->
    <div class="table-container">
      <table class="data-table">
        <thead>
        <tr>
          <th>出库单号</th>
          <th>销售单号</th>
          <th>商品名称</th>
          <th>商品编码</th>
          <th>仓库</th>
          <th>出库数量</th>
          <th>批次号</th>
          <th>库位</th>
          <th>出库状态</th>
          <th>出库时间</th>
          <th>创建时间</th>
          
        </tr>
        </thead>
        <tbody>
        <tr v-for="item in recordsList" :key="item.id">
          <td>{{ item.deliveryCode }}</td>
          <td>{{ item.soId || '-' }}</td>
          <td>{{ item.productName || '未知商品' }}</td>
          <td>{{ item.skuCode || '-' }}</td>
          <td>{{ getWarehouseName(item.warehouseId) }}</td>
          <td class="quantity-cell">{{ item.qty }}</td>
          <td>{{ item.batchNo || '-' }}</td>
          <td>{{ getLocationName(item.locationId) }}</td>
          <td>
            <span :class="getStatusClass(item.status)">{{ getStatusText(item.status) }}</span>
          </td>
          <td>{{ formatDate(item.shippedAt) }}</td>
                     <td>{{ formatDate(item.createdAt) }}</td>
        </tr>
                 <tr v-if="recordsList.length === 0">
           <td colspan="11" class="text-center">暂无数据</td>
         </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页 -->
    <div class="pagination" v-if="pagination.total > 0">
      <div class="pagination-info">
        共{{ Math.ceil(pagination.total / pagination.size) }}页/{{ pagination.total }}条数据
      </div>
      <div class="pagination-controls">
        <button class="btn btn-page" :disabled="pagination.current === 1" @click="changePage(pagination.current - 1)">上一页</button>
        <button
            v-for="page in visiblePages"
            :key="page"
            class="btn btn-page"
            :class="{ active: page === pagination.current }"
            @click="changePage(page)"
        >
          {{ page }}
        </button>
        <button class="btn btn-page" :disabled="pagination.current === Math.ceil(pagination.total / pagination.size)" @click="changePage(pagination.current + 1)">下一页</button>
      </div>
      <div class="pagination-jump">
        <span>跳至</span>
        <input type="number" v-model="jumpPage" min="1" :max="Math.ceil(pagination.total / pagination.size)" />
        <span>页</span>
        <button class="btn btn-small" @click="jumpToPage">确定</button>
      </div>
    </div>


  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { apiGet } from '../../utils/api.js'

// 响应式数据
const recordsList = ref([])
const warehouses = ref([])
const jumpPage = ref(1)

// 搜索表单
const searchForm = reactive({
  deliveryCode: '',
  productName: '',
  warehouseId: '',
  startDate: '',
  endDate: ''
})

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})



// 计算可见页码
const visiblePages = computed(() => {
  const currentPage = pagination.current
  const totalPages = Math.ceil(pagination.total / pagination.size)
  
  if (totalPages <= 5) {
    return Array.from({ length: totalPages }, (_, i) => i + 1)
  }
  
  if (currentPage <= 3) {
    return [1, 2, 3, 4, 5]
  }
  
  if (currentPage >= totalPages - 2) {
    return [totalPages - 4, totalPages - 3, totalPages - 2, totalPages - 1, totalPages]
  }
  
  return [currentPage - 2, currentPage - 1, currentPage, currentPage + 1, currentPage + 2]
})

// 统计信息
const totalRecords = computed(() => pagination.total)
const totalQuantity = computed(() => {
  return recordsList.value.reduce((sum, item) => sum + (parseFloat(item.qty) || 0), 0)
})
const uniqueWarehouses = computed(() => {
  const warehouseIds = new Set(recordsList.value.map(item => item.warehouseId).filter(id => id))
  return warehouseIds.size
})
const uniqueProducts = computed(() => {
  const skuIds = new Set(recordsList.value.map(item => item.skuId).filter(id => id))
  return skuIds.size
})

// 获取出库记录列表
const fetchRecords = async () => {
  try {
    const params = new URLSearchParams({
      page: pagination.current,
      size: pagination.size,
      ...(searchForm.deliveryCode && { deliveryCode: searchForm.deliveryCode }),
      ...(searchForm.productName && { productName: searchForm.productName }),
      ...(searchForm.warehouseId && { warehouseId: searchForm.warehouseId }),
      ...(searchForm.startDate && { startDate: searchForm.startDate }),
      ...(searchForm.endDate && { endDate: searchForm.endDate })
    })

    const data = await apiGet(`/ware-service/ware/delivery/records?${params}`)
    
    if (data.records) {
      recordsList.value = data.records
      pagination.total = data.total || 0
      pagination.current = data.current || 1
    } else {
      recordsList.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取出库记录失败:', error)
    recordsList.value = []
    pagination.total = 0
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.deliveryCode = ''
  searchForm.productName = ''
  searchForm.warehouseId = ''
  searchForm.startDate = ''
  searchForm.endDate = ''
  pagination.current = 1
  fetchRecords()
}

// 页码切换
const changePage = (page) => {
  if (page < 1 || page > Math.ceil(pagination.total / pagination.size)) return
  pagination.current = page
  fetchRecords()
}

// 页码跳转
const jumpToPage = () => {
  const page = Number(jumpPage.value)
  if (page && page >= 1 && page <= Math.ceil(pagination.total / pagination.size)) {
    pagination.current = page
    fetchRecords()
  }
}

// 获取仓库列表
const fetchWarehouses = async () => {
  try {
    const params = new URLSearchParams({
      page: 1,
      size: 100
    })
    
    const data = await apiGet(`/ware-service/warehouse/list?${params}`)
    
    if (data.records) {
      warehouses.value = data.records || []
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    warehouses.value = []
  }
}

// 获取仓库名称
const getWarehouseName = (id) => {
  if (!id) return '-'
  const warehouse = warehouses.value.find(w => w.id === id)
  return warehouse ? warehouse.whName : '-'
}

// 获取库位名称
const getLocationName = (locationId) => {
  if (!locationId) return '-'
  return `库位-${locationId}`
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '草稿',
    1: '待审核',
    2: '已审核',
    3: '已出库'
  }
  return statusMap[status] || '未知'
}

// 获取状态类名
const getStatusClass = (status) => {
  const classMap = {
    0: 'status-info',
    1: 'status-warning',
    2: 'status-success',
    3: 'status-primary'
  }
  return `status ${classMap[status] || ''}`
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString()
}



// 导出记录
const exportRecords = () => {
  // 这里可以实现导出功能
  alert('导出功能待实现')
}

// 生命周期
onMounted(() => {
  fetchRecords()
  fetchWarehouses()
})
</script>

<style scoped>
.outbound-records {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #333;
}

.breadcrumb {
  color: #666;
  font-size: 14px;
}

.search-section {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 16px;
}

.form-item {
  display: flex;
  flex-direction: column;
  min-width: 200px;
}

.form-item label {
  font-size: 14px;
  margin-bottom: 5px;
  color: #333;
}

.form-item input,
.form-item select {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.form-buttons {
  display: flex;
  gap: 10px;
  align-items: flex-end;
  margin-top: 24px;
}

.stats-section {
  margin-bottom: 20px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.stat-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-card:nth-child(2) {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-card:nth-child(3) {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-card:nth-child(4) {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-icon {
  font-size: 24px;
  opacity: 0.8;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
}

.table-container {
  margin-bottom: 20px;
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  border: 1px solid #ddd;
  padding: 10px;
  text-align: left;
}

.data-table th {
  background-color: #f8f9fa;
  font-weight: bold;
}

.data-table tr:nth-child(even) {
  background-color: #f9f9f9;
}

.text-center {
  text-align: center;
}

.quantity-cell {
  font-weight: bold;
  color: #e74c3c;
}

.quantity-text {
  font-weight: bold;
  color: #e74c3c;
  font-size: 16px;
}

.status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-info {
  background-color: #e6f7ff;
  color: #1890ff;
}

.status-warning {
  background-color: #fff7e6;
  color: #fa8c16;
}

.status-success {
  background-color: #e6fffb;
  color: #13c2c2;
}

.status-primary {
  background-color: #f0f5ff;
  color: #2f54eb;
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.pagination-controls {
  display: flex;
  gap: 5px;
}

.pagination-jump {
  display: flex;
  align-items: center;
  gap: 5px;
}

.pagination-jump input {
  width: 50px;
  padding: 4px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.btn-primary {
  background-color: #1890ff;
  color: white;
}

.btn-secondary {
  background-color: #f5f5f5;
  color: #333;
}

.btn-success {
  background-color: #52c41a;
  color: white;
}

.btn-info {
  background-color: #1890ff;
  color: white;
}

.btn-small {
  padding: 4px 8px;
  font-size: 12px;
}

.btn-page {
  padding: 4px 10px;
  min-width: 30px;
  background-color: #fff;
  border: 1px solid #ddd;
}

.btn-page.active {
  background-color: #1890ff;
  color: white;
  border-color: #1890ff;
}



/* 响应式设计 */
@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .form-item {
    min-width: auto;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
}
</style>
